package com.xbjtech.ticketsystem.service;

import com.xbjtech.ticketsystem.mapper.UserMapper;
import com.xbjtech.ticketsystem.model.User;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author leejun.happy@gmail.com
 * @created 2019/2/20
 */
@Service
public class UserService extends BaseService<User> {

    @Autowired
    UserMapper userMapper;

    public User findUserByUserName(String username) {
        return userMapper.findByUserName(username);
    }

    // 批处理
    // 1. 可以用，但是性能不好，优点：开发简单，适合只有30条以内的数据量可以使用这种方式
    // 2. 如果数据量特别大    批处理
    // 批量处理新增修改删除

    @Autowired
    SqlSessionFactory sqlSessionFactory;

    @Transactional
    public void saveList(List<User> list) {

        // 假设list里面有1w个记录 ，当数据量到一个特别大的级别的时候，有可能会造成内存溢出
        // ACID
//        for (User user : list) {
//            userMapper.insertUseGeneratedKeys(user);
//        }

        SqlSession sqlSession = null;
        try {
            sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
            UserMapper mapper = sqlSession.getMapper(UserMapper.class);
            for (int i = 0; i < list.size(); i++) {
                mapper.insertUseGeneratedKeys(list.get(i));
                if (i % 1000 == 0) {
                    sqlSession.commit();
                    sqlSession.clearCache();
                }
            }
            sqlSession.commit();
        } catch (RuntimeException e) {
            sqlSession.rollback();
            throw e;
        }

    }
}
